--读卡服务地址
ip= "192.168.157.135"
--读卡服务端口
port = 5050

--连接到读卡服务
ret = CONNECT(ip,port)                     --建立连接
-------------------------------------------  CPU卡操作
ret,rcv = S_SFI("\x3F\x00",1)              --选择PSAM卡应用3F00
ret,rcv = R_BFile(0x15,0,0,1)              --读取PSAM卡15文件
ret,rcv = R_BFile(0x16,0,0,1)              --读取PSAM卡16文件
if ret == 0x9000 then
	PasmTID = string.sub(rcv,1,12)
	print("pasmTID:"..PasmTID)
end

ret,rcv = S_AID("\xA0\x00\x00\x06\x32\x01\x01\x05",0x08,0)      --选择交通部应用

ret,rcv = R_BFile(0x15,0,0,0)              --读取卡片0x15文件
if ret == 0x9000 then
	MakeCardId = string.sub(rcv,1,16)
	CardASN = string.sub(rcv,25,25+16-1)
	print(rcv)
	print("MakeCardId:"..MakeCardId)
	print("CardASN:"..CardASN)
end
ret,rcv = R_BFile(0x16,0,0,0)

ret,rcv = R_BFile(0x17,0,0,0)    

ret,rcv = S_SFI("\x80\x11",1)              --选择交通部PSAM卡应用

ret,rcv = APDU("805C030204",0)              --读取余额

--消费初始化
cmd = '805001020B'
index = '01'
money = '00000001'

cmdstr = cmd..index..money..PasmTID
print("xiao fei chu shi hua:")
ret,rcv = APDU(cmdstr,0)   --消费初始化
if ret == 0x9000 then
	PullCTC = string.sub(rcv,9,9+4-1)  --脱机交易序号
	KeyVer = string.sub(rcv,19,19+2-1)
	KeyDrk = string.sub(rcv,21,21+2-1)
	Icc =  string.sub(rcv,23,23+8-1)  --随机数
	print("PullCTC:"..PullCTC)
	print("KeyVer:"..KeyVer)
	print("KeyDrk:"..KeyDrk)
	print("Icc:"..Icc)
end

cmd = '8070000024'
time ='20161128170231'
cmdstr = cmd..Icc..PullCTC..money..'06'..time..KeyVer..KeyDrk..CardASN..MakeCardId 

ret,rcv = APDU(cmdstr,1)   --PSAM卡算MAC

if ret == 0x9000 then
	TTC = string.sub(rcv,1,8)  --脱机交易序号
	MAC1 = string.sub(rcv,9,9+8-1)
	print("TTC:"..TTC)
	print("MAC1:"..MAC1)
end

cmd = '805401000F'
cmdstr = cmd..TTC..time..MAC1
ret,rcv = APDU(cmdstr,0)

DISCONNECT()                --断开连接